package cn.edu.zafu.bigdata.sxa;

import java.io.*;
import java.nio.file.*;
import java.util.Scanner;

public class FileAppendRead {

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入您的学号：");
        String studentId = scanner.nextLine();
        String fileName = "files/" + studentId + ".txt";

        System.out.println("请输入您想要追加到文件的文本：");
        String content = scanner.nextLine();

        // 追加内容到文件
        appendToFile(fileName, content);

        // 读取文件并显示内容
        readFile(fileName);

        scanner.close();
    }

    public static void appendToFile(String fileName, String content) {
        try {
            // 确保文件目录存在
            Path dir = Paths.get("files");
            if (!Files.exists(dir)) {
                Files.createDirectories(dir);
            }

            // 追加内容到文件
            Files.write(Paths.get(fileName), content.getBytes(), StandardOpenOption.CREATE, StandardOpenOption.APPEND);
            System.out.println("内容追加成功！");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void readFile(String fileName) {
        try {
            // 读取文件内容
            String content = new String(Files.readAllBytes(Paths.get(fileName)));
            System.out.println("文件内容如下：");
            System.out.println(content);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}